<style lang="stylus" type="text/stylus">
@import 'css/editProcess.styl';
</style>

<template>
  <div id="editProcess">
    <div class="edit-process-header">
      <div class="edit-process-header-con">
        <p>
          <span class="route-title" @click="goBack()">审核流程</span>
          <span class="short-title">&nbsp;<span class="color80859f">/</span>&nbsp;{{getRouteQuery.shortTitle}}</span>
          <span class="page-name">&nbsp;/&nbsp;{{pageName}}</span>
        </p>
        <p class="description">{{pageDescription}}</p>
      </div>
    </div>
    <div class="edit-process-ps">
      <div class="edit-process-con">
        <VuePerfectScrollbar ref="editProcessConPs" class="edit-process-con-ps">
          <div class="edit-process-con-flex">
            <div class="process-child line" v-for="(item,index) in processData.activities" :key="index">
              <div class="process-child-body">
                <div class="process-title">
                  <Input v-model="item.name" placeholder="请命名此环节"></Input>
                </div>
                <div class="card">
                  <div class="title">环节说明</div>
                  <div class="con">
                    <Input type="textarea" class="process-description"
                           v-model="item.description"
                           :autosize="{minRows:2,maxRows:6}"
                           placeholder="请填写环节说明"></Input>
                  </div>
                </div>
                <div class="card">
                  <div class="title">审核主体(以政策划分)</div>
                  <Select :transfer="false" v-if="auditBodyItem.length" :clearable="!0" v-model="item.handler.id"
                          placeholder="请设置审核主体">
                    <OptionGroup :label="item.name" v-for="(item,index) in auditBodyItem"
                                 :key="item.id">
                      <Option v-for="(option,optionIndex) in item.children"
                              :value="option.id" :key="optionIndex">{{option.name}}
                      </Option>
                    </OptionGroup>
                  </Select>
                </div>


                <div class="card">
                  <div class="title">审核模板</div>
                  <div class="con" v-for="(templateInfo,templateInfoIndex) in item.formTemplateList" :key="templateInfoIndex">
                    <a :href="templateInfo.url" target="_blank">{{templateInfo.file_name}}</a>
                    <span @click="delTemplateBtn(templateInfo.id,templateInfo.url,templateInfo.fileInfoId)"><Icon type="ios-close"></Icon></span>
                  </div>
                </div>
                <Upload 
                  :action="uploadUrl"
                  :on-success="handleSuccess"
                  :show-upload-list="false"
                  :data="{moduleName:'help'}">
                    <Button class="uploadBtn" @click="getItemId(item.id,processData.policyId)" type="primary" icon="ios-cloud-upload-outline" long>上传文件</Button>
                </Upload>



                <div class="card activity-forms" @click="auditActiveShow(index)">
                  <div class="title">审核细则</div>
                  <ul v-if="item.activityForms.length">
                    <li v-for="(activity,activityIndex) in item.activityForms" :key="activityIndex">
                      <span class="title-mark">{{activity.formType == 0 ? '单选':'填字'}}</span>
                      <span class="prize-info" :class="{mark:activity.prizeId}">{{prizeInfo(activity.prizeId)}}</span>
                      <p class="description">{{activity.title}}</p>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="btn-tools" v-if="getRouteQuery.pageName && processData.activities.length != 1">
                <span :style="index == 0 ? 'color:#ccc':''" class="up" @click="leftProcess(index)">
                  <Icon type="android-arrow-back"></Icon>
                </span>
                <span :style="index == processData.activities.length-1 ? 'color:#ccc':''" class="down"
                      @click="rightProcess(index)">
                  <Icon type="android-arrow-forward"></Icon>
                </span>
                <span class="del"
                      @click="deleteProcess(index)">
                  <i class="iconfont icon-delete" type="android-delete"></i>
                </span>
              </div>
              <div class="btn-tools-left" v-if="getRouteQuery.pageName">
                <div class="add-left" @click="addActivities(index,true)">
                  <Icon type="ios-plus-empty"/>
                </div>
              </div>
              <div class="btn-tools-right" v-if="getRouteQuery.pageName">
                <div class="add-right" @click="addActivities(index,false)">
                  <Icon type="ios-plus-empty"/>
                </div>
              </div>
            </div>
          </div>
        </VuePerfectScrollbar>
      </div>
    </div>
    <div class="footer">
      <div @click="subAudit()" class="sub btn-com">完成</div>
      <div @click="goBack()" class="cancel btn-com">取消</div>
    </div>

    <Modal
      @on-cancel="closeModal()"
      v-model="auditActive"
      title="设置审核细则">
      <div v-if="activityForms.length" v-for="(item,index) in activityForms" class="activityFormsModal card"
           :key="index">
        <div class="top-title">
          <span class="title-mark">{{item.formType == 0 ? '单选':'选填'}}</span>

          <Dropdown transfer placement="bottom-start" @on-click="selPrize($event,index)" trigger="click"
                    style="margin-left: 4px">
            <a href="javascript:void(0)" class="prize-info" :class="{mark:prizeInfo(item.prizeId)!='通用'}">{{prizeInfo(item.prizeId)}}</a>
            <DropdownMenu slot="list">
              <DropdownItem :name="prize.id"
                            :selected="item.prizeId == prize.id"
                            v-for="(prize,prizeIndex) in prizesItem"
                            :key="prizeIndex">{{prize.title}}
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </div>

        <div class="modal0-con" v-if="item.formType == 0">
          <Input v-model="item.title" type="textarea" :autosize="{minRows:2,maxRows:6}"
                 placeholder="请填写本“单选”的描述文字"></Input>
          <div class="check-items">
            <ul>
              <li v-for="(chk,chkIndex) in item.checkItems" :key="chkIndex">
                <Input v-model="chk.title" placeholder="请命名本选项"><span slot="prepend">选项{{chkIndex+1}}：</span></Input>
                <div class="btn-tools">
                    <span :style="chkIndex == 0 ? 'color:#ccc':''" class="up" @click="modalChildUp(index,chkIndex)">
                     <Icon type="android-arrow-up"></Icon>
                    </span>
                  <span :style="chkIndex == item.checkItems.length-1 ? 'color:#ccc':''" class="down"
                        @click="modalChildDown(index,chkIndex)">
                      <Icon type="android-arrow-down"></Icon>
                    </span>
                  <span class="del" @click="modalChildDelete(index,chkIndex)">
                      <i class="iconfont icon-delete" type="android-delete"></i>
                    </span>
                </div>
              </li>
            </ul>
            <br>
            <Button @click="addActivityFormsSel(index)" type="primary" size="large" long icon="plus">添加选项</Button>
          </div>
        </div>
        <Input v-if="item.formType == 2" type="textarea" v-model="item.title" :autosize="{minRows:2,maxRows:6}"
               placeholder="请填写本“填字”的描述文字"></Input>

        <div class="btn-tools">
                    <span :style="index == 0 ? 'color:#ccc':''" class="up" @click="modalChildUp(index)">
                     <Icon type="android-arrow-up"></Icon>
                    </span>
          <span class="down" :style="index == activityForms.length-1 ? 'color:#ccc':''" @click="modalChildDown(index)">
                      <Icon type="android-arrow-down"></Icon>
                    </span>
          <span class="del" @click="modalChildDelete(index)">
                      <i class="iconfont icon-delete" type="android-delete"></i>
                    </span>
        </div>
      </div>


      <Button @click="auditSelActive = !auditSelActive" type="primary" size="large" long icon="plus">添加审核细则</Button>
      <div slot="footer">
        <Button @click="closeModal()" type="text">取消</Button>
        <Button :disabled="!btnAuditSelActive" type="primary" @click="addAuditSel()" size="large">完成</Button>
      </div>
    </Modal>

    <Modal title="添加审核细则" v-model="auditSelActive">
      <Button @click="auditSel(0)" long>单选</Button>
      <br><br>
      <Button @click="auditSel(2)" long>填字</Button>

      
    </Modal>

    <Modal title="流程配置恢复" :mask-closable="false" :closable="false" v-model="localStorageItemActive">
      <p style="font-size: 16px;color: #333;margin-bottom: 20px;">恢复上一次的流程配置</p>
      <Button @click="subRecovery" type="primary" size="large" style="margin-bottom: 20px;" long>确定恢复</Button>
      <Button @click="delRecovery" type="warning" size="large" long>取消且删除</Button>
      <div slot="footer">
      </div>
    </Modal>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: "editProcess",
  data() {
    return {
      auditBodySel: "",
      auditBodyItem: [],
      auditActive: false,

      prizeId: "",
      prizesItem: [{ title: "通用", id: "" }],

      activityForms: [],
      activityFormsIndex: "",

      processData: {
        id: this.$route.query.id || null,
        policyId: this.$route.query.policyId,
        activities: []
      },

      auditSelActive: false,

      localStorageItemActive: false,
      uploadUrl: this._URL_v2 + "/filecommon/uploadFile",

      activityId: "",
      policyId: ""
    };
  },
  computed: {
    getRouteQuery() {
      return this.$route.query;
    },
    pageName() {
      let name = this.getRouteQuery.pageName;
      return name == "a"
        ? "配置审核流程"
        : name == "b" ? "全局变更" : " 单个环节变更";
    },
    pageDescription() {
      let name = this.getRouteQuery.pageName,
        str = "";
      if (name == "a") {
        str = "配置审核流程";
      } else if (name == "b") {
        str =
          "全局变更生效后,会将该政策所有进行中的审核打回至 未开始 阶段,请谨慎操作!";
      } else {
        str =
          "单个环节变更生效后,会将处于该环节的申请重置至该环节初始阶段,请谨慎操作!";
      }
      return str;
    },
    btnAuditSelActive() {
      let n = !0;
      for (let v of this.activityForms) {
        if (v.formType == 2 && !v.title) {
          n = false;
          break;
        }
        if (v.formType == 0) {
          let c = v.checkItems;
          if (!c.length || !v.title || c.length < 2) {
            n = false;
            break;
          }
          if (c.length) {
            for (let vv of c) {
              if (!vv.title) {
                n = false;
                break;
              }
            }
          }
        }
      }
      return n;
    }
  },
  methods: {
    goBack() {
      this.$router.push({
        name: "reviewProcess",
        query: {
          policyId: this.getRouteQuery.policyId,
          scrolltop: this.getRouteQuery.scrolltop
        }
      });
    },
    // 获取审核主体数据
    getAuditBodySel() {
      this.ajaxData(
        {
          type: "get",
          url: "/workflow/organization/selector"
        },
        (res, all) => {
          if (all.code == 0) {
            this.auditBodyItem = res;
          }
        }
      );
    },
    prizeInfo(id) {
      if (this.prizesItem.length && id) {
        return this.prizesItem.find(item => item.id == id).title;
      } else {
        return "通用";
      }
    },
    // 获取资助数据
    getPrize() {
      this.ajaxData(
        {
          type: "get",
          url: `/dictionary/prize?policyId=${this.getRouteQuery.policyId}`
        },
        (res, all) => {
          if (all.code == 0) {
            this.prizesItem.push(...res);
          }
        }
      );
    },
    // 获取流程数据
    getProcessData() {
      if (this.getRouteQuery.id) {
        let pageName = this.getRouteQuery.pageName,
          url = `/workflow/process/${pageName ? "get" : "getActivity"}?id=${
            this.getRouteQuery.id
          }`;
        this.ajaxData(
          {
            type: "get",
            url: url
          },
          (res, all) => {
            if (all.code == 0) {
              this.processData.activities = pageName
                ? res.activities[1].children
                : [res];
              setTimeout(() => {
                this.$refs.editProcessConPs.update();
              }, 10);
            }
          }
        );
      } else {
        this.processData.activities = [
          {
            id: null,
            name: "",
            description: "",
            handler: {
              id: null,
              name: ""
            },
            activityForms: []
          }
        ];
      }
    },
    // 新建审核主体
    addActivities(index, action) {
      let arr = this.processData.activities;
      const activities = {
        id: "", // 环节ID
        name: "", // 环节名称
        handler: {
          // 审核主体
          id: "", // 审核主体ID（部门/第三方机构ID）
          name: "" // 审核主体名称（部门/第三方机构名称）
        },
        activityForms: []
      };
      let $index = arr.findIndex((v, i) => i == index);
      const editProcessConPs = document.querySelector(".edit-process-con-ps");
      let interval;
      if (interval) {
        clearInterval(interval);
      }
      if (action) {
        arr.splice($index, 0, activities);
        if (index != 0) {
          let left = editProcessConPs.scrollLeft - 420;
          left = left <= 0 ? 0 : left;
          interval = setInterval(function() {
            if (editProcessConPs.scrollLeft <= left && interval) {
              clearInterval(interval);
            }
            editProcessConPs.scrollLeft -= 70;
          }, 10);
        }
      } else {
        arr.splice($index + 1, 0, activities);
        const left = editProcessConPs.scrollLeft + 420;
        interval = setInterval(function() {
          if (editProcessConPs.scrollLeft >= left && interval) {
            clearInterval(interval);
          }
          editProcessConPs.scrollLeft += 70;
        }, 10);
      }

      this.$refs.editProcessConPs.update();
    },
    // 展示审核细则
    auditActiveShow(index) {
      this.auditActive = !this.auditActive;
      this.activityFormsIndex = index;
      let arr = this.processData.activities[index].activityForms;
      for (let v of arr) {
        if (!v.prizeId) {
          v.prizeId = "";
        }
      }
      sessionStorage.setItem("activityForms", JSON.stringify([...arr]));
      let seeeActivityForms = sessionStorage.getItem("activityForms");
      this.activityForms = JSON.parse(seeeActivityForms);
    },
    auditSel(n) {
      let obj = {
        id: null, // 审核细则ID
        prizeId: "", // 资助ID（为空表示通用细则）
        title: "" // 标题
      };
      if (n == 0) {
        Object.assign(obj, {
          formType: 0, // 输入类型：单选（0）、短文本（1）、长文本（2）
          checkItems: []
        });
      } else if (n == 2) {
        Object.assign(obj, {
          formType: 2
        });
      }
      this.activityForms.push(obj);
      this.auditSelActive = !1;
    },
    addActivityFormsSel(index) {
      this.activityForms[index].checkItems.push({
        id: null,
        title: ""
      });
    },
    addAuditSel() {
      let arr = this.processData.activities,
        $index = arr.findIndex((v, i) => i == this.activityFormsIndex);

      let n = !0;
      for (let v of arr[$index].activityForms) {
        if (v.formType == 2 && !v.title) {
          n = false;
          break;
        }
        if (v.formType == 0) {
          let c = v.checkItems;
          if (!c.length || !v.title || c.length < 2) {
            n = false;
            break;
          }
          if (c.length) {
            for (let vv of c) {
              if (!vv.title) {
                n = false;
                break;
              }
            }
          }
        }
      }

      arr[$index].activityForms = this.activityForms;
      this.auditActive = !1;
      this.activityForms = [];
    },
    selPrize(n, index) {
      this.activityForms[index].prizeId = n;
    },
    subAudit() {
      let url = "",
        pageName = this.getRouteQuery.pageName,
        arr = this.processData.activities;
      if (this.getRouteQuery.id) {
        url = pageName
          ? "/workflow/process/update"
          : "/workflow/process/updateActivity";
      } else {
        url = "/workflow/process/new";
      }
      let n = !0;
      for (let v of arr) {
        if (!v.name || !v.handler.id) {
          let str = !v.name ? "请输入环节名字" : "请选择审核主体";
          this.$Message.warning(str);
          n = false;
          break;
        }
      }
      if (n) {
        let processData = pageName
          ? this.processData
          : this.processData.activities[0];
        this.ajaxData(
          {
            type: "post",
            url: url,
            data: processData,
            contentType: "json"
          },
          (res, all) => {
            if (all.code == 0) {
              this.goBack();
            } else if (all.code == 401101) {
              localStorage.setItem(
                "processData",
                JSON.stringify(this.processData)
              );
            }
          }
        );
      }
    },
    closeModal() {
      this.timeLimitActive = false;
      this.auditActive = false;
      this.activityForms = [];
    },
    swapItems(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    },
    leftProcess(index) {
      let arr = this.processData.activities;
      if (arr.length > 1 && index != 0) {
        let x = index,
          y = index - 1;
        this.swapItems(this.processData.activities, x, y);
      }
    },
    rightProcess(index) {
      let arr = this.processData.activities;
      if (arr.length > 1 && index != arr.length - 1) {
        let x = index + 1,
          y = index;
        this.swapItems(this.processData.activities, x, y);
      }
    },
    deleteProcess(index) {
      if (this.processData.activities.length > 1) {
        this.processData.activities.splice(index, 1);
        this.$refs.editProcessConPs.update();
      }
    },
    modalChildUp(index, chkIndex) {
      if (chkIndex && chkIndex > 0) {
        this.swapItems(
          this.activityForms[index].checkItems,
          chkIndex,
          chkIndex - 1
        );
      } else if (chkIndex == undefined && index > 0) {
        this.swapItems(this.activityForms, index, index - 1);
      }
    },
    modalChildDown(index, chkIndex) {
      if (
        chkIndex != undefined &&
        chkIndex !== this.activityForms[index].checkItems.length - 1
      ) {
        this.swapItems(
          this.activityForms[index].checkItems,
          chkIndex + 1,
          chkIndex
        );
      } else if (
        chkIndex == undefined &&
        index !== this.activityForms.length - 1
      ) {
        this.swapItems(this.activityForms, index + 1, index);
      }
    },
    modalChildDelete(index, chkIndex) {
      if (chkIndex != undefined) {
        this.activityForms[index].checkItems.splice(chkIndex, 1);
      } else {
        this.activityForms.splice(index, 1);
      }
    },
    subRecovery() {
      let processData = localStorage.getItem("processData");
      if (processData) {
        this.processData.activities = this.getRouteQuery.pageName
          ? JSON.parse(processData).activities
          : [JSON.parse(processData).activities];
        this.$refs.editProcessConPs.update();
        localStorage.removeItem("processData");
      }
      this.localStorageItemActive = false;
    },
    delRecovery() {
      localStorage.removeItem("processData");
      this.localStorageItemActive = false;
    },
    getItemId(a, b) {
      this.activityId = a;
      this.policyId = b;
    },
    
    handleSuccess(file) {
      let fileInfoId = file.result.id;
      let activityId = this.activityId;
      let policyId = this.policyId;
      this.ajaxData(
        {
          type: "get",
          url: "/workflow/savaNewFormTemplate",
          data: {
            activityId: activityId,
            policyId: policyId,
            fileInfoId: fileInfoId
          }
        },
        res => {
          this.$Message.info("文件上传成功！");
          this.getProcessData();
        }
      );
    },
    delTemplateBtn(id, url, fileInfoId) {
      let formTemplateId = id;
      let filePath = url;
      let fileId = fileInfoId;
      this.ajaxData(
        {
          type: "get",
          url: "/workflow/deleteNewFormTemplate",
          data: {
            formTemplateId: formTemplateId
          }
        },
        res => {
          this.ajaxData(
            {
              type: "get",
              url: "/filecommon/deleteFile",
              data: {
                fileId: fileId,
                filePath: filePath
              }
            },
            res => {
              this.$Message.error("删除成功！");
              this.getProcessData();
            }
          );
        }
      );
    }
  },
  mounted() {
    let processData = localStorage.getItem("processData");
    if (
      processData &&
      this.getRouteQuery.policyId == JSON.parse(processData).policyId
    ) {
      this.localStorageItemActive = !0;
    }
    this.uploadList = this.$refs.upload.fileList;
  },
  created() {
    this.getAuditBodySel();
    this.getPrize();
    this.getProcessData();
  }
};
</script>
